<template>
  <div
    id="app"
    v-cloak
    v-infinite-scroll="scrollLoad"
    infinite-scroll-immediate="false"
    @scroll="scroll"
  >
    <header>
      <section>
        <div>
          <span class="greeting">欢迎您访问长沙长泰智能装备商贸网！</span>
          <el-link
            v-if="isLogin"
            type="info"
            :underline="false"
            class="login"
            >{{ username }}</el-link
          >
          <el-link
            v-else
            type="info"
            :underline="false"
            class="login"
            @click="toLogin"
            >{{ btnTextlogin }}</el-link
          >
        </div>
        <div class="follow">
          <el-popover
            popper-class="popover-m"
            placement="bottom-end"
            trigger="hover"
          >
            <el-image
              style="width: 120px; height: 120px"
              :src="wechatCode"
              fit="fit"
            ></el-image>
            <div slot="reference" class="cursor-pointer">
              <span>微信关注</span><i class="el-icon-arrow-down"></i>
            </div>
          </el-popover>
        </div>
      </section>
    </header>
    <div class="toolbar">
      <nav>
        <el-link :underline="false" @click="goHome">
          <el-image
            style="width: 150px; height: 60px"
            :src="logo"
            fit="fit"
          ></el-image>
        </el-link>
        <div class="search-box">
          <el-input placeholder="输入您想要搜索的产品" v-model="searchKey">
            <el-button
              type="primary"
              slot="append"
              class="btn-search"
              @click="toSearch"
              >搜索</el-button
            >
          </el-input>
        </div>
        <div class="secondary">
          <template v-if="subRecommend.length > 6">
            <template v-for="(item, index) in subRecommend">
              <div :key="item.id" class="item" v-if="index < 6">
                <el-link
                  v-if="index < 5"
                  type="default"
                  :underline="false"
                  :title="item.name"
                  @click="toGoodList(item.id, item.name, item.topid)"
                  >{{ item.name }}</el-link
                >
                <el-popover
                  v-else-if="index === 5"
                  popper-class="popover-mm"
                  placement="bottom-end"
                  trigger="click"
                >
                  <div>
                    <el-link
                      type="default"
                      class="block"
                      :underline="false"
                      @click="
                        toGoodList(
                          subRecommend[5].id,
                          subRecommend[5].name,
                          subRecommend[5].topid
                        )
                      "
                      >{{ subRecommend[5].name }}</el-link
                    >
                    <el-link
                      type="default"
                      class="block"
                      :underline="false"
                      @click="
                        toGoodList(
                          subRecommend[6].id,
                          subRecommend[6].name,
                          subRecommend[6].topid
                        )
                      "
                      >{{ subRecommend[6].name }}</el-link
                    >
                  </div>
                  <div slot="reference" class="cursor-pointer">
                    <el-link class="more" type="default" :underline="false"
                      >更多<i class="el-icon-caret-right"></i
                    ></el-link>
                  </div>
                </el-popover>
              </div>
            </template>
          </template>
          <template v-else>
            <div v-for="item in subRecommend" :key="item.id" class="item">
              <el-link
                type="default"
                :underline="false"
                :title="item.name"
                @click="toGoodList(item.id, item.name, item.topid)"
                >{{ item.name }}</el-link
              >
            </div>
          </template>
        </div>
      </nav>
    </div>
    <main>
      <router-view />
    </main>
    <footer>
      地址：湖南省长沙市雨花经济开发区新兴路268号&nbsp;&nbsp;&nbsp;&nbsp;邮编：410116&nbsp;&nbsp;&nbsp;&nbsp;
      电话：86-731-88238288&nbsp;&nbsp;&nbsp;&nbsp;长沙长泰智能装备有限公司
    </footer>
    <el-link :underline="false" class="btn-top" @click="goTop" v-if="showBtnTop"
      ><i class="iconfont iconfanhuidingbu"></i
    ></el-link>

    <el-dialog
      :visible.sync="dialogLogin.visible"
      custom-class="dialog-login"
      :close-on-click-modal="dialogLogin.closeOnClickModal"
      :close-on-press-escape="dialogLogin.closeOnPressEscape"
      append-to-body
      element-loading-background="rgba(0, 0, 0, 0.1)"
      @close="closeDialogLogin"
    >
      <div v-if="isCustomer" key="customer">
        <div class="title">客户登录</div>
        <el-form
          :model="formDataCustomer"
          :rules="rulesCustomer"
          ref="customerLogin"
          label-position="top"
        >
          <el-form-item label="账号" prop="account">
            <el-input
              size="medium"
              class="border-bottom"
              v-model="formDataCustomer.account"
              placeholder="请输入"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              size="medium"
              class="border-bottom"
              v-model="formDataCustomer.password"
              placeholder="请输入"
              autocomplete="off"
              type="password"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="w-100" @click="loginCustomer"
          >登录</el-button
        >
        <div class="footer">
          <el-link
            type="primary"
            :underline="false"
            @click="changeLoginType('visitor')"
            >游客登录</el-link
          >
        </div>
      </div>
      <div v-else key="visitor">
        <div class="title">游客授权码登录</div>
        <el-form
          :model="formDataVisitor"
          :rules="rulesVisitor"
          ref="visitorLogin"
          label-position="top"
        >
          <el-form-item label="授权码" prop="code">
            <el-input
              size="medium"
              class="border-bottom"
              v-model="formDataVisitor.code"
              placeholder="请输入"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button type="primary" class="w-100" @click="loginVisitor"
          >登录</el-button
        >
        <div class="footer">
          <el-link
            type="primary"
            :underline="false"
            @click="changeLoginType('customer')"
            >客户登录</el-link
          >
        </div>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogInquiry.visible"
      custom-class="dialog-inquiry"
      :close-on-click-modal="dialogInquiry.closeOnClickModal"
      :close-on-press-escape="dialogInquiry.closeOnPressEscape"
      append-to-body
      element-loading-background="rgba(0, 0, 0, 0.1)"
    >
      <div class="title">当前商品编号 {{ goodId }}</div>
      <div class="image">
        <el-image
          style="width: 160px; height: 160px"
          :src="wechatCode"
          fit="fit"
        ></el-image>
      </div>
      <div class="title">微信扫码进入公众号咨询</div>
      <span slot="footer" class="dialog-footer">
        <span class="item">{{ linkman }}</span>
        <i class="item iconfont iconxiugaishoujihaoma-01"></i>
        <span class="item phone">{{ telephone }}</span>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getModelRecommend, loginVisitor, loginCustomer } from "@/api/api.js";
import md5 from "md5";
export default {
  data() {
    return {
      isLogin: false, // 是否登录
      isCustomer: true,
      username: "", // 登录人名称
      btnTextlogin: "[登录]",

      logo: require("./assets/logo.png"),
      searchKey: "", // 检索关键词
      subRecommend: [], // 副推
      dialogLogin: {
        visible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
      },
      formDataCustomer: {
        account: "",
        password: "",
      },
      formDataVisitor: {
        code: "",
      },
      rulesCustomer: {
        account: [
          {
            required: true,
            message: "账号不能为空",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur",
          },
        ],
      },
      rulesVisitor: {
        code: [
          {
            required: true,
            message: "授权码不能为空",
            trigger: "blur",
          },
        ],
      },
      showBtnTop: false,
    };
  },
  created() {
    this.$store.dispatch("user/getCodeValue");
    this.$store.dispatch("user/updateContactInformation");
    this.getModelRecommend();
    this.checkLogin();
    this.checkHistory();
  },
  methods: {
    checkLogin() {
      let mallLoginInfo = null;
      try {
        mallLoginInfo = JSON.parse(localStorage.getItem("mallLoginInfo"));
        try {
          let userInfo = JSON.parse(localStorage.getItem("userInfo"));
          let token = localStorage.getItem("token");
          if (userInfo && token) {
            mallLoginInfo.token = token;
            mallLoginInfo.username = userInfo.name;
          }
        } catch (e) {
          // console.info(e)
        }
      } catch (e) {
        // console.info(e)
      }
      console.info("登录信息", mallLoginInfo);
      if (mallLoginInfo) {
        this.isLogin = true;
        this.username = mallLoginInfo.username
          ? mallLoginInfo.username
          : "游客";
      }
    },
    checkHistory() {
      if (this.$router.currentRoute.name === "GoodsList") {
        let goodsListParams = null;
        try {
          goodsListParams = JSON.parse(localStorage.getItem("goodsListParams"));
          this.$store.dispatch("user/getGoodsList", goodsListParams);
        } catch (e) {
          // console.info(e)
        }
      } else if (this.$router.currentRoute.name === "Search") {
        let keyword = localStorage.getItem("keyword");
        this.searchKey = keyword;
        this.$store.dispatch("user/searchGoods", { keyword });
      }
    },
    loginVisitor() {
      this.$refs.visitorLogin.validate((valid) => {
        if (valid) {
          loginVisitor(this.formDataVisitor).then((res) => {
            console.info("游客登录成功", res);
            this.$refs.visitorLogin.resetFields();
            this.dialogLogin.visible = false;
            this.$message.success("登录成功");
            let mallLoginInfo = { code: res.data };
            localStorage.setItem(
              "mallLoginInfo",
              JSON.stringify(mallLoginInfo)
            );
            window.location.reload();
          });
        } else {
          return false;
        }
      });
    },
    loginCustomer() {
      this.$refs.customerLogin.validate((valid) => {
        let params = {
          account: this.formDataCustomer.account,
          password: md5(this.formDataCustomer.password),
          autoLogin: true,
          language: "zh",
        };
        if (valid) {
          loginCustomer(params).then((res) => {
            console.info("客户登录成功", res);
            this.$refs.customerLogin.resetFields();
            this.dialogLogin.visible = false;
            this.$message.success("登录成功");
            let mallLoginInfo = {
              token: res.data.token,
              username: res.data.userName,
            };
            localStorage.setItem(
              "mallLoginInfo",
              JSON.stringify(mallLoginInfo)
            );
            window.location.reload();
          });
        } else {
          return false;
        }
      });
    },
    changeLoginType(type) {
      if (type === "visitor") {
        this.$refs.customerLogin.resetFields();
        this.isCustomer = false;
      } else if (type === "customer") {
        this.$refs.visitorLogin.resetFields();
        this.isCustomer = true;
      }
    },
    getModelRecommend() {
      getModelRecommend({}).then((res) => {
        console.info("副推", res?.data?.subRecommend);
        this.subRecommend = res?.data?.subRecommend;
      });
    },
    toGoodList(firstCategory, firstCategoryName, topid) {
      this.$store.dispatch("user/getGoodsList", {
        firstCategory,
        firstCategoryName,
        deviceType: topid,
      });
      if (this.$router.currentRoute.name !== "GoodsList") {
        this.$router.push({ path: "/goodsList" });
      }
    },
    toSearch() {
      this.$store.dispatch("user/searchGoods", { keyword: this.searchKey });
      if (this.$router.currentRoute.name !== "Search") {
        this.$router.push({ path: "/search" });
      }
    },
    toLogin() {
      if (this.isLogin) {
        //
      } else {
        this.dialogLogin.visible = true;
      }
    },
    closeDialogLogin() {},
    goHome() {
      if (this.$router.currentRoute.name !== "Home") {
        this.$router.push({ path: "/" });
      }
    },
    scrollLoad() {
      this.$store.commit("user/setScroll");
    },
    scroll(event) {
      let scrollTop = event.target.scrollTop;
      if (scrollTop > 150) {
        this.showBtnTop = true;
      } else {
        this.showBtnTop = false;
      }
    },
    goTop() {
      console.log("goback函数被执行");
      this.showBtnTop = false;
      this.$el.scrollTop = 0;
    },
  },
  computed: {
    wechatCode() {
      return this.$store.state.user.contactInformation.photo;
    },
    dialogInquiry() {
      return this.$store.state.user.dialogInquiry;
    },
    goodId() {
      return this.$store.state.user.goodId;
    },
    linkman() {
      return this.$store.state.user.contactInformation.name;
    },
    telephone() {
      return this.$store.state.user.contactInformation.telephone;
    },
  },
};
</script>

<style lang="scss">
.el-breadcrumb {
  padding-left: 50px;
  position: relative;
}
.el-breadcrumb::before {
  content: "位置：" !important;
  color: #606266;
  position: absolute;
  top: 0;
  left: 0;
}
.el-breadcrumb__inner a,
.el-breadcrumb__inner.is-link {
  font-weight: normal !important;
  color: #606266 !important;
}
.breadcrumb-a {
  cursor: pointer;
}
.popover-m {
  min-width: 140px !important;
  line-height: 0 !important;
}
.popover-mm {
  min-width: 100px !important;

  .block {
    display: block;
    font-size: 13px;
  }
  .block:not(:first-child) {
    margin-top: 10px;
  }
}
.dialog-login {
  width: 640px !important;
  height: 400px;
  position: absolute !important;
  top: 0 !important;
  bottom: 0 !important;
  left: 0 !important;
  right: 0 !important;
  margin: auto !important;
  border-radius: 4px !important;
  background-image: url("./assets/login.png") !important;
  background-position: 0 0 !important;
  background-repeat: no-repeat !important;

  .el-dialog__body {
    position: absolute;
    width: 320px;
    height: 360px;
    right: 0;
    bottom: 0;
    padding: 0 40px;
  }
  .title {
    font-family: Microsoft YaHei;
    font-style: normal;
    font-weight: bold;
    font-size: 20px;
    line-height: 26px;
    color: #c0c4cc;
    text-align: center;
    padding-bottom: 20px;
    border-bottom: 1px solid #f2f6fc;
    margin-bottom: 20px;
  }
  label {
    line-height: 14px !important;
  }
  .w-100 {
    width: 100%;
  }
  .footer {
    text-align: center;
    position: absolute;
    left: 0;
    right: 0;
    bottom: 22px;
  }
}
.dialog-inquiry {
  width: 282px !important;
  border-radius: 10px !important;
  overflow: hidden;

  .el-dialog__body {
    padding: 20px;
  }

  .title {
    font-size: 14px;
    line-height: 18px;
    color: #606266;
    text-align: center;
  }
  .image {
    margin: 20px auto;
    text-align: center;
  }
  .el-dialog__footer {
    text-align: center;
    color: #ffffff;
    background: #0d7fff;
    padding: 13px;
    height: 52px;
    .dialog-footer {
      font-size: 14px;

      .item {
      }

      .iconfont {
        font-size: 12px;
        padding-left: 10px;
        padding-right: 2px;
      }
      .phone {
        font-size: 20px;
        position: relative;
        top: 2px;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #303133;
  overflow: auto;
}

.btn-top {
  position: fixed;
  right: calc((100% - 1200px) / 2 - 48px - 20px);
  bottom: 77px;
  width: 48px;
  height: 48px;
  font-size: 22px;
  background-color: #3378ff;
  color: #ffffff !important;
}

header {
  padding: 0px;
  font-size: 13px;
  position: fixed;
  z-index: 999;
  height: 31px;
  width: 100%;
  left: 0px;
  top: 0px;

  background: #fafafa;
  border: 1px solid #ebeef5;

  section {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    width: 1200px;
    height: 100%;
    margin: 0 auto;

    .login {
      margin-left: 10px;
      font-size: 13px;
      vertical-align: inherit;
    }
    .cursor-pointer {
      cursor: pointer;
    }
  }
}

.toolbar {
  // position: fixed;
  // z-index: 999;
  // top: 31px;
  // left: 0;
  // right: 0;
  margin-top: 31px;
  background-color: #ffffff;
  padding-top: 15px;
  padding-bottom: 15px;

  nav {
    width: 1200px;
    margin: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search-box {
      width: 684px;

      ::v-deep .el-input-group__append {
        background-color: #3378ff;
        border-color: #3378ff;
        color: #ffffff;
      }

      ::v-deep .el-input__inner {
        border-width: 2px;
        border-color: #3378ff;
      }

      .btn-search {
        width: 117px;
      }
    }

    .secondary {
      max-width: 285px;
      min-width: 150px;
      text-align: left;

      .item {
        max-width: 93px;

        padding: 4px 7.5px;
        display: inline-block;

        ::v-deep .el-link {
          font-size: 13px;

          .el-link--inner {
            min-width: 0;
            max-width: 80px;
            min-width: 60px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }

        .more {
          color: #606266;

          i {
            color: #dcdfe6;
          }
        }
      }
    }
  }
}
main {
  // margin-top: 123px;
  margin-bottom: 100px;
}

footer {
  position: fixed;
  z-index: 999;
  left: 0;
  right: 0;
  bottom: 0;
  height: 57px;
  line-height: 57px;
  background: #606266;
  font-size: 13px;
  color: rgba(255, 255, 255, 0.75);
}
</style>
